import React, { Component } from 'react';
import { connect } from 'dva';
import { Modal, Spin, Tree, Form, message, Checkbox, Row, Col } from 'antd';
const { TreeNode } = Tree;

@connect(({ authManage, loading }) => ({
  authManage,
  loading: loading.effects['authManage/getUsers'],
}))


class AuthTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      defaultExpandedKeys: [],
      checkedKeysResult: []
    }
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.setState({
      checkedKeys: nextProps.authList,
      defaultExpandedKeys: nextProps.defaultExpandedKeys
    })
  }

  onExpand = expandedKeys => {
    this.setState({ expandedKeys, autoExpandParent: false, });
  };

  onCheck = (checkedKeys, e) => {
    this.setState({ checkedKeys });
  };

  onSelect = (selectedKeys, info) => {
    this.setState({ selectedKeys });
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.menuId ? item.menuId : item.parentId} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      };
      return <TreeNode key={item.menuId ? item.menuId : item.parentId} {...item} />;
    });

  onCreate = () => {
    const { checkedKeys } = this.state;
    if (checkedKeys.length === 0) {
      return message.info('请选择权限完再点击确定')
    };
    this.props.onCreate(checkedKeys);
    this.setState({
      checkedKeys: [],
      checkedKeysResult: []
    })
  };

  render() {
    const { visible, onCancel, userInfo, loading, authList, treeData } = this.props;
    const { checkedKeys, defaultExpandedKeys } = this.state;
    return (
      <Modal visible={visible} title="添加编辑权限" okText="保存" onCancel={onCancel} onOk={this.onCreate}>
        <Spin spinning={false}>
          <Tree
            checkable
            onExpand={this.onExpand}
            expandedKeys={this.state.expandedKeys}
            autoExpandParent={this.state.autoExpandParent}
            onCheck={this.onCheck}
            checkedKeys={checkedKeys}
            onSelect={this.onSelect}
            selectedKeys={this.state.selectedKeys}
          >
            {this.renderTreeNodes(userInfo)}
          </Tree>
          {/*<Checkbox.Group style={{ width: '100%' }} onChange={this.onChange}>
            <Row>
              {treeData.map((tree, index) => {
                return (
                  <Col span={4} key={index}>
                    <Checkbox value={tree.key} key={index}>{tree.title}</Checkbox>
                  </Col>
                );
              })}
             </Row>
          </Checkbox.Group>*/}
        </Spin>
      </Modal>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(AuthTree));
